import sdk from '../../index';
import { baseClass } from "../../tool/baseClass";
import { BattleArea } from "../battleArea";
import component, { ComType } from "../../tool/component";
import client_component from "../../../component/client_component";

export class BaseBody  extends baseClass {
    id: string = sdk.tool.common.uuid;
    _master:BaseBody | null = null;
    componentMap: Map<string, component> = new Map();
    constructor() {
        super();
    }
    setMaster(master:BaseBody){
        this._master = master;
    }
    getComponent(name: ComType): any {
        let _name = name + '_component';
        let com = this.componentMap.get(name);
        if (!com) {
            const sceneModule = sdk.component.getComponent(_name) as any;
            com = new sceneModule() as component;
            com.setBody(this,this._master);
            com.init();
            this.componentMap.set(name, com);
        }
        return com;
    }
    getMaster(){
        return this._master || this;
    }
    hasComponent(name: string) {
        let _name = name + '_component';
        return this.componentMap.get(_name);
    }
    delComponent(name: string) {
        this.componentMap.delete(name);
    }
    addComponent(name: string, component: component) {
        this.componentMap.set(name, component);
    }
    client_text(text: string) {
        let clientCom = this.getComponent(ComType.client) as client_component;
        clientCom.client_text(text);
    }
    client_img(name:string,data:any){
        let clientCom = this.getComponent(ComType.client) as client_component;
        clientCom.client_img(name,data);
    }
    async save(){
        let coms = [...this.componentMap.values()];
        let saveData = {
            id:this.id,
            componentMap:[] as any[]
        };
        for(let com of coms){
            saveData.componentMap.push(com.resave());
        }
        return saveData;
    }
    load(data:any){
        this.id = data.id;
        let saveData = data;

        for(let com of saveData.componentMap){
            let _com = this.getComponent(com.clsName.split('_component')[0] as ComType);
            if(!com){
                continue;
            }
            _com.reload(com);
        }
    }
}